﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Threading;

namespace System.Common
{
  [DebuggerStepThrough]
  [DebuggerNonUserCode]
  public class WeakDelegate : IDisposable
  {
    [DebuggerBrowsable( DebuggerBrowsableState.Never )]
    private WeakReference fRef;

    public object Target
    {
      get
      {
        if ( fRef == null || !fRef.IsAlive )
          return null;

        return fRef.Target;
      }

      set
      {
        if ( fRef != null )
        {
          fRef.Target = null;
          fRef = null;
        }

        if ( value != null )
          fRef = new WeakReference( value );
      }
    }

    public MethodInfo Method { get; set; }

    public static Dispatcher Dispatcher
    {
      get { return Dispatcher.CurrentDispatcher; }
    }

    #region IDisposable Members

    public void Dispose()
    {
      if ( fRef == null )
        return;

      if ( fRef.Target != null || fRef.IsAlive )
        fRef.Target = null;

      fRef = null;
    }

    #endregion
  }
}
